﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Markup;
using CncConvProg.View.Dialog;
using CncSimple.MainApp.SplashScreen;
using Framework.Abstractions.Wpf.Intefaces;

namespace CncSimple.MainApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private DateTime _appStart;

        public App()
        {
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
            Startup += Application_Startup;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Exit += Application_Exit;
        }


        private void Application_Startup(object sender, StartupEventArgs e)
        {
            _appStart = DateTime.Now;

            try
            {

                // Check if this was launched by double-clicking a doc. If so, use that as the
                // startup file name.
                if (AppDomain.CurrentDomain.SetupInformation
                   .ActivationArguments.ActivationData != null
                && AppDomain.CurrentDomain.SetupInformation
                   .ActivationArguments.ActivationData.Length > 0)
                {

                    var fname = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];

                    // It comes in as a URI; this helps to convert it to a path.
                    var uri = new Uri(fname);
                    fname = uri.LocalPath;

                    this.Properties["ArbitraryArgName"] = fname;

                }

            }
            catch (Exception ex)
            {
                // For some reason, this couldn't be read as a URI.
                // Do what you must...
            }

            try
            {
                var splashScreenWindow1 = new SplashScreenWindow1();
                splashScreenWindow1.Show();

                var cultureName = Thread.CurrentThread.CurrentCulture.Name;
                var xmlLang = XmlLanguage.GetLanguage(cultureName);
                FrameworkElement.LanguageProperty.OverrideMetadata(
                    typeof(FrameworkElement),
                    new FrameworkPropertyMetadata(xmlLang));

                Bootstrapper.InitializeIoc();

                var vw = new View.ShellWiew();

                MainWindow = vw;

                ShutdownMode = ShutdownMode.OnMainWindowClose;

                vw.Show();

                splashScreenWindow1.CloseSplashScreen();
            }
            catch (Exception)
            {
                throw;
            }

        }

        private void WriteReport(string error)
        {
            if (!RptSen.ReportGenerator.PcId.CheckInternetConnection.IsConnectedToInternet()) return;

            using (var s = new ServiceReference1.Service1Client())
            {
                var timeSpan = DateTime.Now.Subtract(_appStart).TotalMinutes;

                var mi = RptSen.ReportGenerator.PcId.GetPcId();

                s.Rep(timeSpan, mi.MacAddress, error, string.Empty);
            }

        }
        private void Application_Exit(object sender, EventArgs e)
        {
#if RELEASE
            try
            {
                WriteReport("Success Ending");

            }
            catch (Exception)
            {

            }
#endif
        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //If the app is running outside of the debugger then report the exception using
            //the browser's exception mechanism. On IE this will display it a yellow alert 
            //icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {
#if RELEASE

                try
                {
                    WriteReport(MapException(e.ExceptionObject as Exception));

                    Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;

                    Current.Shutdown(1);

                }
                catch (Exception)
                {

                }
#endif

            }
        }

        private string MapException(Exception ex)
        {
            var template = "Message : {0} \n" +
                              "Data : {1} \n" +
                              "Source : {2} \n " +
                              "Inner Exception : {3} \n" +
                              "TargetSite : {4} \n" +
                              "HelpLink : {5} \n" +
                              "Stack Trace : {6} ";

            return string.Format(template, ex.Message, ex.Data, ex.Source, ex.InnerException, ex.TargetSite, ex.HelpLink, ex.StackTrace);

        }
    }
}
